require 'socket'

def get_arguments
  host = ARGV[0]
  port = ARGV[1].to_i
  if host.nil? or host == '' or port < 1 then
    puts "[usage] chat <host> <port>"
    exit(1);
  end
  return host, port
end

def start_receiver(host, port)
  return Thread.new do
    sock = nil
    begin
      sock = TCPSocket.open(host, port)
      while true
        sock.write("get:\n")
        puts sock.gets
      end
    ensure
      sock.close unless sock.nil?
    end
  end
end

def start(host, port)
  sock = nil
  begin
    sock = TCPSocket.open(host, port)
    while line = STDIN.gets.to_s.chomp
      break if line == ':q'
      sock.write("post:" + line + "\n")
      #p sock.gets
    end
  ensure
    sock.close unless sock.nil?
  end
end

def main
  host, port = get_arguments
  rt = start_receiver(host, port)
  start(host, port)
  Thread.kill(rt)   # おおお？
end

if __FILE__ == $0 then
  main
end
